<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Models\DragDetail;
use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderCancel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:cancel';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动取消订单';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $leftTime = 2 * 60;//暂定两分钟前的订单未付款将取消资格
        Order::where('pay_status', 0)->where('status', 0)->where('created_at', '<', time() - $leftTime)->orderBy('id', 'asc')->chunkById(100, function ($list) {
            foreach ($list as $item) {
                DB::beginTransaction();
                try {
                    $item->status        = -1;
                    $item->cancel_at     = time();
                    $item->cancel_reason = '超时未付款自动取消';
                    $item->save();
                    $goodsList = $item->goods_snap;
                    if (!empty($goodsList)) {
                        foreach ($goodsList as $value) {
                            if ($value['num'] > 0) {
                                DragDetail::where('drag_id', $item['dragon_id'])->where('id', $value['id'])->increment('store', $value['num']);
                                Log::info('团购数据' . $item['dragon_id'] . '商品' . $value['id'] . '库存因订单取消恢复成功');
                            }
                        }
                    }
                    DB::commit();
                } catch (\Exception $exception) {
                    Log::error('订单取消失败' . $exception->getMessage());
                    DB::rollBack();
                }

            }

        });


    }

}
